<?php
/**
 * Created by PhpStorm.
 * User: mww
 * Date: 2019/8/30
 * Time: 14:26
 */
namespace app\apiteacher\controller;
use think\Db;
class Index extends Base {
    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
        $user_id2 = input('user_id');
        $time = input('time');
        $value = input('value');
        $reqKey = input('reqKey');
        $auth = $this->checkAll($user_id2,$time,$value,$reqKey);
        if($auth == 112){
            echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
            exit;
        }elseif($auth == 110){
            echo json_encode(['status' => 302, 'msg' => $this->frost]);
            exit;
        }elseif($auth == 2111){
            echo json_encode(['status' => 303, 'msg' => $this->del]);
            exit;
        }
    }
    /** 首页之：学生求助（只显示对我的）
     * type : 0全部 1未回复  2已回复  3 已关闭
     * @return \think\response\Json
     */
    public function index(){
        extract(input());
        $page = input('param.page')?input('param.page'):1;
        $num = 15;
        $limit = $page-1;
        $where = array();
        if($type > 0){
            $where['course_status'] = $type;
        }
        $field = 'a.*,user_username,grade_name,subject_name';
        $where['course_teacher_id'] = $user_id;
        $res = Db::table('up_course')->alias('a')
            ->join('up_subject us','us.subject_id = a.course_subject_id','left')
            ->join('up_u_user u','u.user_id = a.course_user_id','left')
            ->join('up_grade g','u.user_grade = g.grade_id','left')
            ->where($where)
            ->order('course_time desc')
            ->field($field)
            ->limit($num*$limit,$num)
            ->select();
        return  json(array('status'=>200,'msg'=>$res));
    }
    
    //热门城市
    public function hot(){
        $where['level'] = 2;
        $where['hot'] = 1;
        $res =  Db::table('up_area')->where($where)->select();
        return  json(array('status'=>200,'msg'=>$res));
    }
    
    /** 在线学生模块（只显示公开的）
     * type : 0全部 1未回复  2已回复  3 已关闭
     * @return \think\response\Json
     */
    public function indexForTwo(){
        extract(input());
        //先把有可能的我点击了没答题退出去了的都改成原始状态
        Db::table('up_course')
            ->where('course_status',1)
            ->where('course_teacher_id',-1)
            ->where('course_click_uid',$user_id)
            ->setField('course_click_uid',0);

        $page = input('param.page')?input('param.page'):1;
        $num = 15;
        $limit = $page-1;
        $where = array();
        $my = Db::table('up_u_user')->where('user_id',$user_id)->field('user_subject,user_grade')->find();
        $field = 'a.*,user_username,grade_name,subject_name';
        $where['course_teacher_id'] = -1;
        $where['course_status'] = ['in','1,2'];
        $where['course_subject_id'] = $my['user_subject'];
        $where['user_grade'] = $my['user_grade'];
        if(isset($keyword) && $keyword){
            $where['course_content'] = array('like',"%$keyword%");
        }
        //course_status==1 && course_click_uid为0的显示那个答题按钮
        $res = Db::table('up_course')->alias('a')
            ->join('up_subject us','us.subject_id = a.course_subject_id','left')
            ->join('up_u_user u','u.user_id = a.course_user_id','left')
            ->join('up_grade g','u.user_grade = g.grade_id','left')
            ->where($where)
            ->order('course_time desc')
            ->field($field)
            ->limit($num*$limit,$num)
            ->select();
        $count = Db::table('up_course')->alias('a')
            ->join('up_subject us','us.subject_id = a.course_subject_id','left')
            ->join('up_u_user u','u.user_id = a.course_user_id','left')
            ->join('up_grade g','u.user_grade = g.grade_id','left')
            ->where($where)
            ->count();
        $subject = Db::table('up_subject')->order('subject_sort asc')->select();
        return  json(array('status'=>200,'msg'=>$res,'my'=>$my,'count'=>$count,'subject'=>$subject));
    }
    /**
     * 求助详情
     * course_id
     * @return \think\response\Json
     */
    public function detail(){
        extract(input());
        $where['course_id'] = $course_id;
        $field = 'a.*,user_username,user_image';
        $res = Db::table('up_course')->alias('a')
            ->join('up_u_user u','u.user_id = a.course_user_id','left')
            ->where($where)
            ->field($field)
            ->find();
        $res['user_exper'] = Db::table('up_u_user')->where('user_id',$user_id)->value('user_exper');
        //我能不能看--start--
        Db::table('up_course')
            ->where('course_status',1)
            ->where('course_teacher_id',-1)
            ->where('course_click_uid',$user_id)
            ->setField('course_click_uid',0);
        $can = $this->canISolve($res,$user_id);
        if($can['status'] != 200){
            return  json($can);
        }
        //--end--
        if($res['course_status']==2){
            $data = Db::table('up_course_reply')->where('reply_course_id',$course_id)->find();
            $res['data'] = $data;
        }
        $map['evaluate_course_id'] = $course_id;
        $result = Db::table('up_evaluate')->field('evaluate_star,evaluate_content')->where($map)->find();
        $res['result'] = $result;
        return  json(array('status'=>200,'msg'=>$res));
    }

    /**
     * 进去但是没有解答返回了
     * 只有返回200才可以真正退出
     */
    public function solveBack(){
        extract(input());
        $where['course_id'] = $course_id;
        $res = Db::table('up_course')->where($where)->setField('course_click_uid',0);
        if($res){
            return  json(array('status'=>200,'msg'=>''));
        }else{
            return  json(array('status'=>100,'msg'=>'请刷新'));
        }
    }
    /**
     * 进去答题
     * 只有返回200才可以真正进入
     */
    public function solveIn(){
        extract(input());
        $where['course_id'] = $course_id;
        $res = Db::table('up_course')->where($where)->find();
        //我能不能答题--start--
        $can = $this->canISolve($res,$user_id);
        if($can['status'] != 200){
            return  json($can);
        }else{
            $res2 = Db::table('up_course')->where($where)->update([
                'course_click_uid' => $user_id,
                'course_click_time' => date('Y-m-d H:i:s')
            ]);
            if($res2){
                return  json(array('status'=>200,'msg'=>''));
            }else{
                return  json(array('status'=>100,'msg'=>'请刷新重试'));
            }
        }
        //--end--
    }

    /**
     * 答题
     * @return \think\response\Json
     */
     public function answer(){
         extract(input());
         $ccuid = Db::table('up_course')->where('course_id',$course_id)
             ->field('course_click_uid,course_user_id')->find();
         if($ccuid['course_click_uid'] != $user_id){
             return  json(array('status'=>100,'msg'=>"您已超时或不可答题，请重新进入"));
         }
         $data['reply_course_id'] = $course_id;
         $data['reply_user_id'] = $user_id;
         $data['reply_content'] = $content;
         $data['reply_img'] = $img;
         $data['reply_time'] = date('Y-m-d H:i:s',time());
         Db::startTrans();
         try{
             //1、入回复
             Db::table('up_course_reply')->insert($data);
             //2、改状态和时间
             Db::table('up_course')->where('course_id',$course_id)->update([
                 'course_status' => 2,
                 'course_answer_time' => date('Y-m-d H:i:s',time())
             ]);
             // 增加经验分
             Db::table('up_u_user')->where('user_id', $user_id)->setInc('user_exper');
             Db::commit();
             //3、入消息表
             allInNotice('求助回复','有老师回复了你的问题,快来看看~',1,2,3,$course_id,$ccuid['course_user_id']);
             //4、推送
             $list = [];//需要推送的用户数组
             $val = (string)($ccuid['course_user_id']);
             array_push($list, $val);
             try{
                 $this->JpushS(1, $list, '求助回复', ['reply_course_id' => $course_id, 'send_type' => 3]);
             }catch(\Exception $e){

             }
             return  json(array('status'=>200,'msg'=>"成功"));
         }catch (\Exception $e) {
             Db::rollback();
             return  json(array('status'=>100,'msg'=>"失败"));
         }
     }

    /**
     * 学生列表和搜索
     * @return \think\response\Json
     */
    public function userLists(){
        extract(input());
        $where = array();
        $where['user_type'] = 1;
        $where['user_status'] = ['<',4];
        if(isset($keyword) && $keyword){
            $where['user_username|userid'] = array('like',"%$keyword%");
        }
        if(isset($shi) && $shi && $shi>0){
            $where['user_shi'] = $shi;
        }
        $likes = Db::table('up_follow_user')->alias('fu')
            ->join('up_u_user u','fu.follow_quilt_user_id = u.user_id','left')
            ->where($where)
            ->where('follow_user_id',$user_id)
            ->column('follow_quilt_user_id');

        $field1 = 'user_id,user_username,user_image,grade_name,subject_name,district,user_gender,fu.indexorder';
        $field2 = 'user_id,user_username,user_image,grade_name,subject_name,district,user_gender,u.indexorder';
        $data_1 = Db::table('up_follow_user')->alias('fu')
            ->join('up_u_user u','fu.follow_quilt_user_id = u.user_id','left')
            ->join('up_area a','u.user_shi = a.district_id','left')
            ->join('up_subject s','u.user_subject = s.subject_id','left')
            ->join('up_grade g','u.user_grade = g.grade_id','left')
            ->where($where)
            ->where('follow_user_id',$user_id)
            ->order('user_letter asc')
            ->page($page,10)
            ->field($field1)
            ->select();
        //判断依据--start--
        $like_nums = count($likes);
        $yu = $like_nums % 10;
        $shang = ceil($like_nums / 10);
        //判断依据-- end --
        if($data_1){ //如果数据存在，说明未关注的一定是从0开始，数量是减去取余值
            $limit = 0;
            $limit_num = 10 - count($data_1);
        }else{
            if($shang > 0){ //商($like_nums也可)大于0说明此老师有关注的学生，但没有数据，说明一定要取出10条，关键是从哪一个开始取
                if($yu == 0){ //因为商大于0，若余为0，则说明正好是10的整倍数，要减去10，其他情况则减去余
                    $yu = 10;
                }
                $limit = ($page-$shang)*10-$yu;
                $limit_num = 10;
            }else{ //商小于0说明此老师没有关注的学生，直接用分页
                $limit = ($page-1)*10;
                $limit_num = 10;
            }
        }
        if($limit_num >= 1){ //如果数量为0，有可能sql中取的是全部
            if($like_nums >= 1){
                $where['user_id'] = ['not in',$likes];
            }
            $data_2 = Db::table('up_u_user')->alias('u')
                ->join('up_area a','u.user_shi = a.district_id','left')
                ->join('up_subject s','u.user_subject = s.subject_id','left')
                ->join('up_grade g','u.user_grade = g.grade_id','left')
                ->where($where)
                ->order('user_letter')
                ->limit($limit,$limit_num)
                ->field($field2)
                ->select();
            $res = array_merge($data_1,$data_2);
        }else{
            $res = $data_1;
        }
        return json(['status' => 200, 'msg' => $res]);
    }
    /**
     * 关注和取消关注
     * @return \think\response\Json
     */
    public function likeOrNo(){
        extract(input());
        $where = array();
        $where['follow_user_id'] = $user_id;
        $where['follow_quilt_user_id'] = $other_id;
        $likes = Db::table('up_follow_user')
            ->where($where)
            ->find();
        if($likes){
            $res = Db::table('up_follow_user')
                ->where($where)
                ->delete();
        }else{
            $where['follow_time'] = date('Y-m-d H:i:s',time());
            $res = Db::table('up_follow_user')->insert($where);
        }
        if($res){
            return json(['status' => 200, 'msg' => '操作成功']);
        }else{
            return json(['status' => 100, 'msg' => '操作失败']);
        }
    }

}